// pages/exam/exam-record/exam-record.ts
// 定义类型
interface ExamRecord {
  id: number;
  paperId: number;
  startTime: string;
  endTime: string;
  totalScore: number; //总题数｜总分数
  userTotal: number; //答题数
  userScore: number; //答对数｜得分
  passStatus: boolean | false;
  paperName: string;
  examPeriod: number;
}
interface ExamPaper {
  id: number;
  paperCode: string;
  paperName: string;
  totalScore: number;
  passScore: number;
  duration: number;
  status: string;
}


Page({
  data: {
    paperId: 0, // 试卷ID
    examPaper: {} as ExamPaper,
    examRecords: [] as ExamRecord[],
    isThesisPaper: false // 添加属性用于判断是否为论文题
  },

  onLoad(options: any) {
    const paperId = parseInt(options.paperId);
    this.setData({ paperId });
    //debugger
    this.loadExamRecords(paperId);
  },

  async loadExamRecords(paperId?: number) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    // 如果不传paperId，则使用data中的paperId
    paperId = paperId || this.data.paperId;
    try {
      const response = await this.getExamRecords(paperId);
      console.log("examRecords:" + JSON.stringify(response.data.pageInfo.list as ExamRecord[]));
      const records = response.data.pageInfo.list.map((record: { userScore: number; userTotal: number; }) => ({
        ...record,
        // 预先计算颜色值，当准确率大于等于60%时显示绿色，否则显示红色
        accuracyColor: this.getAccuracyColor(record.userScore, record.userTotal),
        // 计算进度条宽度（实际应该是得分率）
        progressWidth: `${(record.userScore / record.userTotal * 100).toFixed(0)}%`
      }));

      // 判断是否为论文题
      const examPaper = response.data.examPaper as ExamPaper;
      const isThesisPaper = examPaper.paperName && examPaper.paperName.includes('论文题');

      this.setData({
        examPaper: examPaper,
        examRecords: records as ExamRecord[],
        isThesisPaper: isThesisPaper
      })
    } catch (error) {
      console.error('加载分类数据失败:', error);
      wx.showToast({ title: '加载失败', icon: 'error' });
    } finally {
      wx.hideLoading();
    }
  },

  // 从网络获取分类数据
  async getExamRecords(paperId: number): Promise<Object> {
    const app = getApp<IAppOption>();

    return new Promise((resolve, reject) => {
      //debugger
      wx.request({
        // url: `http://192.168.16.113:8080/api/exam/records?paperId=${paperId}&page=1&size=5`,
        url: app.buildApiUrl(`/api/exam/records?paperId=${paperId}&page=1&size=5`),
        method: 'GET',
        header: { 'Authorization': wx.getStorageSync('token') },
        success: (res) => {
          if (res.statusCode === 200) {

            console.log("res.data:" + JSON.stringify(res.data));
            //resolve(res.data.data.pageInfo.list as ExamRecord[]);
            resolve(res.data);
          } else {
            reject(new Error(`请求失败，状态码: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  getAccuracyColor(userScore: number, userTotal: number) {
    // 当准确率大于等于60%时返回绿色，否则返回红色
    if ((userScore / userTotal * 100) >= 60) return 'green';
    return 'red';
  },

  async startExam() {
    const examRecord = await this.examStart(this.data.paperId);
    const recordId = examRecord.id;
    wx.navigateTo({
      // url: '/pages/exam/exam?paperId=' + this.data.paperId
      url: `/pages/exam/exam-start/exam-start?paperId=${this.data.paperId}&recordId=${recordId}`

    })
  },
  continueExam: function (e: { 
    currentTarget: { 
      dataset: { 
        recordid: any; 
        paperid: any; 
      }; 
    }; 
    }) {
    const recordId = e.currentTarget.dataset.recordid;
    const paperId = e.currentTarget.dataset.paperid;

    wx.navigateTo({
      url: `/pages/exam/exam-start/exam-start?paperId=${paperId}&recordId=${recordId}`

    })
  },
  async startReview() {
    const examRecord = await this.examStart(this.data.paperId);
    const recordId = examRecord.id;
    wx.navigateTo({
      //url: '/pages/exam/exam-beiti/exam-beiti?paperId=' + this.data.paperId
      url: `/pages/exam/exam-beiti/exam-beiti?paperId=${this.data.paperId}&recordId=${recordId}`

    })
  },


  // 记录开始答题
  async examStart(paperId: number): Promise<ExamRecord> {
    const app = getApp<IAppOption>();

    return new Promise((resolve, reject) => {
      wx.request({
        url: app.buildApiUrl('/api/exam/start'),
        method: 'POST',
        header: { 'Authorization': wx.getStorageSync('token') },
        data: { paperId }, // 传入paperId参数
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data.data as ExamRecord);
          } else {
            wx.showToast({
              title: '请求失败: ' + res.statusCode,
              icon: 'error',
              duration: 2000
            });
            reject(new Error(`请求失败，状态码: ${res.statusCode}`));
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '请求失败',
            icon: 'error',
            duration: 2000
          });
          reject(err);
        }
      });
    });
  },

  startWrong() {
    wx.navigateTo({
      url: '/pages/exam/exam?mode=wrong'
    })
  },

  // 查看完整记录
  viewRecord: function (e: { currentTarget: { dataset: { recordid: any; paperid: any; status: any; }; }; }) {
    const recordId = e.currentTarget.dataset.recordid;
    const paperId = e.currentTarget.dataset.paperid;
    const status = e.currentTarget.dataset.status;
    // const { paperId } = this.data;
    // debugger
    if (status == 1) {
      wx.navigateTo({
        url: `/pages/exam/exam?paperId=${paperId}&recordId=${recordId}`
      });
    } else {
      console.log("navigate by viewRecord");
      wx.navigateTo({
        url: `/pages/exam/exam-detail/exam-detail?paperId=${paperId}&recordId=${recordId}&recordType=0`
      });
    }

  },

  // 仅看错题
  viewWrongOnly: function (e: { currentTarget: { dataset: { recordid: any; paperid: any; }; }; }) {
    // // 阻止事件冒泡，避免触发父元素的viewRecord事件
    // e.stopPropagation();

    const recordId = e.currentTarget.dataset.recordid;
    const paperId = e.currentTarget.dataset.paperid;
    // const { paperId } = this.data;

    console.log("navigate by viewRecord");
    wx.navigateTo({
      url: `/pages/exam/exam-detail/exam-detail?paperId=${paperId}&recordId=${recordId}&recordType=1`
    });
  }
})